<script setup>
import * as api from '@/api/store/product.js'
import * as apiStore from "@/api/store/store.js"
import { getLocalTime } from "@/utils/time.js"
import { ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash'
import { ref, onMounted } from 'vue'

/* ----- search ----- */
const searchOption = ref({
  name: null,
})
const storeNameList = ref([])
const storeNameMap = ref({})
const typeList = ref([
  {label: '商品', value: 0},
  {label: '赠品', value: 1},
])

function search() {
  reqPage()
}

/* ----- table ----- */
const pn = ref(1)
const ps = ref(10)
const total = ref(0)
const tableList = ref([])
const tableListDisp = ref([])

async function reqSave() {
  const result = await api.reqSave(form.value)

  if (result != null) {
    ElMessage({
      message: '新增成功',
      type: 'success',
    })
    await reqPage()
  }
}

async function reqUpdate() {
  const result = await api.reqUpdate(form.value)

  if (result != null) {
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
    await reqPage()
  }
}

async function reqDelete(id) {
  const result = await api.reqDelete(id)

  if (result != null) {
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    await reqPage()
  }
}

async function reqBan(id, banFlag) {
  const result = await api.reqBan(id, banFlag)

  if (result != null) {
    ElMessage({
      message: banFlag == 0 ? '启用成功' : '禁用成功',
      type: 'success',
    })
    await reqPage()
  }
}

async function reqPage() {
  const result = await api.reqPage(
    pn.value,
    ps.value,
    searchOption.value.name
  )

  if (result.code === '0') {
    total.value = result.data.total
    tableList.value = []
    tableListDisp.value = []
    result.data.items.forEach(item => {
      tableList.value.push(cloneDeep(item))
      tableListDisp.value.push(cloneDeep(item))
      tableListDisp.value[tableListDisp.value.length - 1].productionDate = getLocalTime(item.productionDate, 1)
      tableListDisp.value[tableListDisp.value.length - 1].createTime = getLocalTime(item.createTime)
      tableListDisp.value[tableListDisp.value.length - 1].updateTime = getLocalTime(item.updateTime)
    })
  }
}

/* ----- dialog ----- */
const dialogVisible = ref(false)
const formType = ref(0)
const formSaveDefault = {
  name: null,
  type: null,
  description: null,
  storeId: null,
}
const formUpdateDefault = {
  id: null,
  name: null,
  type: null,
  description: null,
  storeId: null,
}
const form = ref(formSaveDefault)

function openDialog(index) {
  // 新增
  if (index == null) {
    formType.value = 0
    confirm = reqSave
    form.value = formSaveDefault
  }
  // 修改
  else {
    formType.value = 1
    confirm = reqUpdate
    form.value = formUpdateDefault
    for (let k in form.value) {
      form.value[k] = tableList.value[index][k]
    }
  }

  dialogVisible.value = true
}

function cancel() {
  dialogVisible.value = false
}

function confirm() {
  if (formType.value == 0) {
    reqSave()
  }
  else if (formType.value == 1) {
    reqUpdate()
  }

  dialogVisible.value = false
}


const getStoreNameList = async ()=>{
  await apiStore.reqStoreNameList().then(resp => {
    storeNameList.value = resp.data.items.map(x => {
      return { label: x.name, value: x.id }
    })
    // 使用普通对象作为映射表
    storeNameMap.value = resp.data.items.reduce((map, x) => {
      map[x.id] = x.name;
      return map;
    }, {});
  })
}


/* ----- init ----- */
onMounted(()=>{
  reqPage()
  getStoreNameList()
})
// apiStore.reqStoreNameList().then(resp => {
//   storeNameList.value = resp.data.items.map(x => {
//     return { label: x.name, value: x.id }
//   })
// })

</script>

<template>
  <!-- ----------------------------------- search ----------------------------------- -->
  <el-card>
    <el-scrollbar always>
      <el-form class="search-card">
        <div class="search-input">
          <el-form-item label="货品名">
            <el-input placeholder="请输入货品名" v-model="searchOption.name" clearable></el-input>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" size="default" @click="search" >搜索</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!-- ----------------------------------- search ----------------------------------- -->

  <!-- ----------------------------------- table ----------------------------------- -->
  <el-card>
    <el-button type="primary" size="default" @click="openDialog(null)">添加货品</el-button>
    <el-table style="margin: 10px 0;" border :data="tableListDisp">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="货品名" align="center" width="200px" prop="name" show-overflow-tooltip></el-table-column>
      <el-table-column label="分店" align="center" prop="storeId" show-overflow-tooltip>
        <template #="{row}">
          <span>{{ storeNameMap[row.storeId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type" show-overflow-tooltip>
        <template #="{row}">
          <p>{{ typeList[row.type].label }}</p>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" show-overflow-tooltip></el-table-column>
      <el-table-column label="数量" align="center" prop="number" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="状态" align="center" prop="banFlag" show-overflow-tooltip>
        <template #="{ row, $index}">
          <p v-if="row.banFlag === 0"></p>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{ row, $index }">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" icon="Edit" @click="openDialog($index)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-popconfirm :title="`确定要删除?`" width="260px" @confirm="reqDelete(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-button type="warning" size="small" icon="Edit" @click="reqBan(row.id, 1)">禁用</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="success" size="small" icon="Edit" @click="reqBan(row.id, 0)">启用</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <RouterLink :to="`/log/deal/product-number/?productId=${row.id}`">
                <el-button :style="{ backgroundColor: '#7e57c2', color: '#fff', borderColor: '#7e57c2' }" size="small">货品订单数量管理</el-button>
              </RouterLink>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <RouterLink :to="`/log/deal/product-payment/?productId=${row.id}`">
                <el-button  :style="{ backgroundColor: '#ff7043', color: '#fff', borderColor: '#ff7043' }" size="small">货品订单金额管理</el-button>
              </RouterLink>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="reqPage"
        @current-change="reqPage"
        v-model:current-page="pn"
        v-model:page-size="ps"
        :page-sizes="[3, 5, 7, 10]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
    />
  </el-card>
  <!-- ----------------------------------- table ----------------------------------- -->

  <!-- ----------------------------------- dialog ----------------------------------- -->
  <el-dialog
      v-model="dialogVisible"
      :title="formType == 0 ? '添加货品' : '修改货品'"
  >
    <el-form style="width: 80%" :model="form">
      <el-form-item label="货品名" label-width="100px">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="类型" label-width="100px">
        <el-select v-model="form.type" clearable placeholder="类型" style="width:180px">
          <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" label-width="100px">
        <el-input v-model="form.description" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="分店名" label-width="100px">
        <el-select v-model="form.storeId" clearable placeholder="分店名" style="width:180px">
          <el-option
              v-for="item in storeNameList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
  <!-- ----------------------------------- dialog ----------------------------------- -->
</template>

<style scoped lang="css">
.search-card {
  display: flex;
  align-items: center;
  flex-direction: row;
}
.search-input {
  display: flex;
  align-items: center;
  flex: 1 0 auto;
}
.search-input > * {
  flex: 0 1 auto;
  margin-right: 2rem;
}
.search-card .el-form-item {
  margin-bottom: 0;
}
.el-card {
  margin-bottom: 2rem;
}
</style>
